package org.istt.web;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletContext;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.apache.struts2.ServletActionContext;
import org.istt.domain.WorkflowProcess;
import org.istt.service.FileManager;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionSupport;

/**
 *
 * @author 
 */
public class FileProcessVoucherExport extends ActionSupport {
	
	private static final long serialVersionUID = 3338690462530238561L;
	InputStream wordStream;
	String documentFormat = "doc";

	private String id;
	private FileManager manager;
	private Set<WorkflowProcess> workflowProcesses;
	private List<Object[]> fileProcessVoucher;
	
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
	
	@Autowired
	public void setFileManager(FileManager manager) {
		this.manager = manager;
	}
	
	public String toMSWord() throws IOException, InvalidFormatException, CloneNotSupportedException {
	    
	    workflowProcesses = ((FileManager)manager).get(id).getCategory().getWorkflow().getWorkflowProcesses();
	    
	    ServletContext servletContext = ServletActionContext.getServletContext();
	    String filePath = servletContext.getRealPath("/word/Phieu_kiem_soat_tien_do_ho_so.docx");
	    org.istt.domain.File fileMgn = ((FileManager)manager).get(id);
	    fileProcessVoucher = ((FileManager)manager).getFileProcessVoucher(id);
	    File file = new File(filePath);
	    InputStream inp = new FileInputStream(file);
	    
	    XWPFDocument docx = new XWPFDocument(inp);
	    Iterator<XWPFTable> range=docx.getTablesIterator();

        XWPFTable table=range.next();
        XWPFTable table2=range.next();
        //System.out.println(table2.getText());
        
        
      //header
		List<XWPFParagraph> paragraphs = docx.getParagraphs();
		
		for (int x=0; x<paragraphs.size();x++)
		{
			XWPFParagraph paragraph = paragraphs.get(x);
			XWPFRun r = paragraph.createRun();
			String dateStr = fileMgn.getOutputDate().toString();
//			System.out.println("x: "+x+" ----" +paragraph.getParagraphText());
			switch(x)
			{
			  case 1:
				  r.setText(fileMgn.getCategory().getCategoryName()); 
				  r.setBold(false);
				  r.setFontFamily("Times New Roman");
				  break;
			  case 3:
				  r.setText(fileMgn.getContactName()); 
				  r.setBold(false);
				  r.setFontFamily("Times New Roman");
				  break;
			  case 4:
				  r.setText(fileMgn.getLocation()); 
				  r.setBold(false);
				  r.setFontFamily("Times New Roman");
				  break;
			  case 5:
				  r.setText(fileMgn.getId()); 
				  r.setBold(false);
				  r.setFontFamily("Times New Roman");
				  break;
			  case 7:
				  r.setText("Ng\u00E0y "+dateStr.substring(8, 10)+" th\u00E1ng "+dateStr.substring(5, 7)+" n\u0103m "+dateStr.substring(0, 4)); 
				  r.setBold(false);
				  r.setFontFamily("Times New Roman");
				  break;
			}
		}
        
	    Float totalDoneTime = 0f;
	    Float totalRequiredTime = 0f;

	    //draw table
	    for (int i = 1; i <= workflowProcesses.size(); i++) {
	    	for (WorkflowProcess w : workflowProcesses) {
	    		if (w.getPosition().equals(i)) {
		    		Float requiredTime = new Float(w.getProcessTime());
		    		totalRequiredTime += requiredTime;
		    		XWPFTableRow row1 = table2.createRow();
		            row1.createCell();
		            row1.createCell();
		    		ParagraphAlignment align = ParagraphAlignment.CENTER;
		    		row1.getCell(0).getParagraphs().get(0).setAlignment(align );
		    		
		            XWPFRun r1 = row1.getCell(1).getParagraphs().get(0).createRun();
		            r1.setText(w.getProcessStatus().getDescription());//col#2:description
		            r1.setBold(false);
		            r1.setFontFamily("Times New Roman"); 
		            
		            XWPFRun r2 = row1.getCell(0).getParagraphs().get(0).createRun();
		            r2.setText(Integer.toString(i));//col#1:index
		            r2.setBold(false);
		            r2.setFontFamily("Times New Roman"); 
		            
		            XWPFRun r3 = row1.getCell(2).getParagraphs().get(0).createRun();
		            r3.setText(w.getProcessTime() + "");//col#3: required time
		            r3.setBold(false);
		            r3.setFontFamily("Times New Roman"); 
		    		//row1.getCell(0).setText(Integer.toString(i));
		    		//row1.getCell(1).setText(w.getProcessStatus().getDescription());
		    		//row1.getCell(2).setText(w.getProcessTime());
		            
		    		for (int j = 0; j < fileProcessVoucher.size(); j++) {
		    			if (i==j+1) {
//			    	        Float doneTime = new Float(fileProcessVoucher.get(j)[0]);
		    				//Fixed by Thond.2012.03.07
		    				Float doneTime = new Float(0);
		    				if(fileProcessVoucher.get(j)[0]!=null)
		    						doneTime = new Float(fileProcessVoucher.get(j)[0] + "");
		    				totalDoneTime += doneTime;
			    	        
			    	    	XWPFRun r4 = row1.getCell(3).getParagraphs().get(0).createRun();
			                r4.setText(doneTime + "");//col#4: done time
			                r4.setBold(false);
			                r4.setFontFamily("Times New Roman");
			                
	            	    	XWPFRun r5 = row1.getCell(6).getParagraphs().get(0).createRun();
			                //r5.setText(fileProcessVoucher.get(j)[2]);//col#7:comment
			                //Fixed by NDTHO.2012.03.01
	            	    	r5.setText(StringUtils.trim((String)fileProcessVoucher.get(j)[2]));
			                r5.setBold(false);
			                r5.setFontFamily("Times New Roman"); 
			                
			                //col#8: approver (approve date)
			    	    	XWPFRun r6 = row1.getCell(7).getParagraphs().get(0).createRun();
			    	    	if(StringUtils.trim((String)fileProcessVoucher.get(j)[1]) != null)
			    	    		r6.setText(StringUtils.trim((String)fileProcessVoucher.get(j)[1]) + "\n" + StringUtils.trim((String)fileProcessVoucher.get(j)[3]));
			    	    	else
			    	    		r6.setText("(Ch\u01B0a k\u00FD)"+ "\n" +StringUtils.trim((String)fileProcessVoucher.get(j)[3]));
			    	    	
			                r6.setBold(false);
			                r6.setFontFamily("Times New Roman");
			                
			                if(fileProcessVoucher.get(j)[7]!=null){
			                	if (fileProcessVoucher.get(j)[7].equals(true)) {
			                		XWPFRun r7 = row1.getCell(4).getParagraphs().get(0).createRun();
			                		r7.setText("X");//col#5: is approve?
			                		r7.setBold(false);
			                		r7.setFontFamily("Times New Roman"); 
			                	}
			                	if (fileProcessVoucher.get(j)[7].equals(false)) {
			                		XWPFRun r7 = row1.getCell(5).getParagraphs().get(0).createRun();
			                		r7.setText("X");//col#6: is reject?
			                		r7.setBold(false);
			                		r7.setFontFamily("Times New Roman"); 
			                	}		                
			                }
		    			}
		    		}
	    		}
	    	}
        
	    }
        XWPFTableRow row2 = table2.createRow();
        row2.createCell();
        row2.createCell();
        XWPFRun r4 = row2.getCell(1).getParagraphs().get(0).createRun(); 
        r4.setText("T\u1ED5ng c\u1ED9ng");
        r4.setBold(true);
        r4.setFontFamily("Times New Roman");        
        row2.getCell(2).setText(totalRequiredTime + "");//total required time

		
  	    //total required time
    	XWPFRun r1 = row2.getCell(3).getParagraphs().get(0).createRun();
        r1.setText(totalDoneTime + "");
        r1.setBold(false);
        r1.setFontFamily("Times New Roman"); 
        

/*	 for (int x = 0; x < range.numSections(); x++) {
            Section s = range.getSection(x);
            for (int y = 0; y < s.numParagraphs(); y++) {
                    Paragraph p = s.getParagraph(y);
                    String paraText = p.text();
                    int offset1 = paraText.indexOf("pos1");
                    if (offset1 != -1) {
                            System.out.println("REPLACED "+offset1);
                            p.replaceText("pos1", fileMgn.getCategory().getCategoryName(), offset1);
                    }
                    
                    int offset2 = paraText.indexOf("pos2");
                    if (offset2 != -1) {
                            System.out.println("REPLACED "+offset2);
                            p.replaceText("pos2", fileMgn.getContactName(), offset2);
                    }
                    
                    int offset3 = paraText.indexOf("pos3");
                    if (offset3 != -1) {
                            System.out.println("REPLACED "+offset3);
                            p.replaceText("pos3", fileMgn.getLocation(), offset3);
                    } 
                    
                    int offset4 = paraText.indexOf("pos4");
                    if (offset4 != -1) {
                            System.out.println("REPLACED "+offset4);
                            p.replaceText("pos4", fileMgn.getId(), offset4);
                    }                      
                    
                    int offset5 = paraText.indexOf("pos5");
                    if (offset5 != -1) {
                    	String dateStr = fileMgn.getOutputDate();
                            System.out.println("REPLACED "+offset5);
                            p.replaceText("pos5", "Ng\u00E0y "+dateStr.substring(8, 10)+" th\u00E1ng "+dateStr.substring(5, 7)+" n\u0103m "+dateStr.substring(0, 4), offset5);
                    }                     
            }

    } */
	    
	    
	    
	    //write to word file
	    ByteArrayOutputStream baos = new ByteArrayOutputStream();
	    docx.write(baos);
	    wordStream = new ByteArrayInputStream(baos.toByteArray());

	    return SUCCESS;
	}

	String getWordContentType() {
		return documentFormat == "doc" ? "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" : "application/msword";
	}
	
	
	public InputStream getWordStream() {
		return wordStream;
	}


	public void setWorkflowProcesses(Set<WorkflowProcess> workflowProcesses) {
		this.workflowProcesses = workflowProcesses;
	}

	public Set<WorkflowProcess> getWorkflowProcesses() {
		return workflowProcesses;
	}

	public void setFileProcessVoucher(List<Object[]> fileProcessVoucher) {
		this.fileProcessVoucher = fileProcessVoucher;
	}

	public List<Object[]> getFileProcessVoucher() {
		return fileProcessVoucher;
	}

		
}
